package com.wcgksoft.controller.system;


import com.wcgksoft.common.filter.shiro.CaptchaToken;
import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.admin.Account;
import com.wcgksoft.entity.system.SysMenu;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.SysMenuService;
import com.wcgksoft.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;


/**
 * @author 蒋世维
 * <p>
 * 项目名称：gardens
 * 类名称：IndexController
 * 类描述：登录验证
 * 创建人：jiangshiwei
 * 创建时间：2018-12-27 PM12:59:08
 * 修改备注：
 * @version 1.0.0
 */
@Controller
@RequestMapping("login")
public class LoginManageController {

  @Autowired
  private UserService userService;


  @Autowired
  private SysMenuService sysMenuService;


  /**
   * 启动 登陆页
   *
   * @return
   */
  @RequestMapping(value = "index")
  public String link(ModelMap modelMap) {
    return "login";
  }


  /**
   * @return
   */
  //  +@ResponseBody 才能被ajax接收
  @ResponseBody
  //  请求映射 == url
  @RequestMapping(value = "verification", method = RequestMethod.POST)
  public Layui verification(
          ModelMap modelMap, HttpServletRequest request, HttpServletResponse response, Model model,
          @RequestParam(value = "userName", required = false) String userName,
          //请求参数  @RequestParam(value = "对应参数", required = false) String passWord //别名
          @RequestParam(value = "passWord", required = false) String passWord) {
    try {
      System.out.println(request.getSession().getAttribute("KAPTCHA_SESSION_KEY"));
      String username = request.getParameter("userName");
      String pwd = request.getParameter("passWord");
      String captchacode = request.getParameter("captchacode");
      CaptchaToken token = new CaptchaToken(username, pwd, captchacode);
      Subject currentUser = SecurityUtils.getSubject();

      //没有登录的用户进行登录
      if (!currentUser.isAuthenticated()) {
        currentUser.login(token);
      }

      Locale locale = Locale.SIMPLIFIED_CHINESE;
      Date date = new Date();
      DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
      String formattedDate = dateFormat.format(date);

      model.addAttribute("currentUser", username);
      model.addAttribute("serverTime", formattedDate);
    } catch (UnknownAccountException uae) {
      // 用户名未知...
      System.out.println("用户不存在" + uae);
      model.addAttribute("errorMsg", "用户不存在");
      return Layui.data(403, "用户不存在", 1, null);
    } catch (IncorrectCredentialsException ice) {
      // 凭据不正确，例如密码不正确 ...
      System.out.println("密码不正确" + ice);
      model.addAttribute("errorMsg", "密码不正确");
      return Layui.data(403, "密码不正确", 1, null);
    } catch (LockedAccountException lae) {
      // 用户被锁定，例如管理员把某个用户禁用...
      System.out.println("用户被禁用" + lae);
      model.addAttribute("errorMsg", "用户被禁用");
      return Layui.data(403, "用户被禁用" + lae, 1, null);
    } catch (ExcessiveAttemptsException eae) {
      // 尝试认证次数多余系统指定次数 ...
      System.out.println("请求次数过多，用户被锁定" + eae);
      model.addAttribute("errorMsg", "请求次数过多，用户被锁定");
      return Layui.data(403, "请求次数过多，用户被锁定" + eae, 1, null);
    } catch (Exception ex) {
      System.out.println("未知错误，无法完成登录" + ex);
      model.addAttribute("errorMsg", "未知错误，无法完成登录");
      return Layui.data(403, "验证码不正确", 1, null);
    }
    Account sysUser = (Account) SecurityUtils.getSubject().getSession().getAttribute("om_user");


    //-----------------------》查询自己关系下的菜单
 /*   if (null != sysUser.getSysRole()) {
      List<SysMenu> onemenu = new ArrayList<>();
      List<SysMenu> twomenu = new ArrayList<>();
      Set<SysMenu> sysMenuSet = sysUser.getSysRole().getSysMenuSet();

      Iterator<SysMenu> iterator = sysMenuSet.iterator();
      while (iterator.hasNext()) {
        SysMenu s = iterator.next();
        if (s.getParentId() == -1) {
          onemenu.add(s);
          //iterator.remove();
        }else{
          twomenu.add(s);
        }
      }
      for (SysMenu menu : onemenu) {
        List<SysMenu> list = new ArrayList<>();
        for (SysMenu sysMenu : twomenu) {
            if (sysMenu.getParentId()==menu.getId()){
              list.add(sysMenu);
            }
        }
        menu.setSysMenus(list);
      }
      request.getSession().setAttribute("menu", onemenu);
    }
*/

    return Layui.data(0, "查询成功", 1, null, sysUser);
  }

  /**
   * 登录成功后跳转到主页
   *
   * @return
   */
  @RequestMapping(value = "main")
  public String main(HttpServletRequest request, ModelMap modelMap) {
    return "main";
  }

  /**
   * 修改密码
   *
   * @return
   */

  @RequestMapping(value = "updatepasswold")
  public Layui updatepasswold(HttpServletRequest request, @RequestParam String passworld) {
    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    if (sysUser != null) {
      sysUser.setPassWord(passworld);
      userService.saveOrUpdate(sysUser);
      return Layui.data(1, "修改成功", 1, null);
    } else {
      return Layui.data(0, "请登陆", 1, null);
    }

  }


  /**
   * 修改个人信息
   *
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "updateuser")
  public Layui updateuser(HttpServletRequest request, @RequestParam(value = "phone") String phone, @RequestParam String name,
                          @RequestParam String idCard, @RequestParam String sex,
                          @RequestParam String telePhone, @RequestParam String email, @RequestParam String companyName,
                          @RequestParam Integer funds, @RequestParam String address
          /*@RequestParam String birthDate*/
  ) throws ParseException {
    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");*/
    if (sysUser != null) {
      sysUser.setPhone(phone);
      sysUser.setName(name);
      sysUser.setIdCard(idCard);
      sysUser.setSex(sex);
      sysUser.setTelePhone(telePhone);
      sysUser.setEmail(email);
      sysUser.setCompanyName(companyName);
      sysUser.setFunds(funds);
      sysUser.setAddress(address);
      /*user.setBirthDate(sdf.parse(birthDate));*/
      userService.saveOrUpdate(sysUser);
      return Layui.data(1, "修改成功", 1, null);
    } else {
      return Layui.data(0, "修改失败", 1, null);
    }

  }

}
